package com.hoas.api.config;

import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.util.Assert;

import java.nio.charset.Charset;

public class StringRedisSerializer implements RedisSerializer<String> {
    private final Charset charset;

    private String prefix = "";

    public StringRedisSerializer() {
        this(Charset.forName("UTF8"));
    }

    public StringRedisSerializer(Charset charset) {
        Assert.notNull(charset, "Charset must not be null!");
        this.charset = charset;
    }

    public String deserialize(byte[] bytes) {

        return bytes == null ? null : (prefix == null || prefix.length() == 0 ? "" : prefix + "_") + new String(bytes, this.charset);
    }

    public byte[] serialize(String string) {
        return string == null ? null : ((prefix == null || prefix.length() == 0 ? "" : prefix + "_") + string).getBytes(this.charset);
    }

    public String getPrefix() {
        return prefix;
    }

    public void setPrefix(String prefix) {
        this.prefix = prefix;
    }

}
